<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Lang;
use app\common\model\Advertise as AdvertiseModel;
use app\common\model\User;
use think\Validate;

/**
 * Ajax异步请求接口
 * @internal
 */
class Advertise extends Frontend
{

    protected $noNeedLogin = ['lang'];
    protected $noNeedRight = ['*'];
    protected $layout = 'layout';

    /**
     * (任务栏)我发布的任务列表
     * 'draft','wait','pass','finish','refuse'
     * @param int $page 页数
     * @param string $status 任务状态
     * @return [type] [description]
     */
    public function myadvertise()
    {
       
            $advertise = new AdvertiseModel();
            $total=$advertise->where('user_id',$this->auth->id)->count();
            $advertises=$advertise
                ->where('user_id',$this->auth->id)->order('id desc')
                ->paginate(10);

         
        return $this->view->fetch('',['rows'=>$advertises]);
    }

/**
     * 发布任务 || 存为草稿
     *
     * @param int $id 编辑广告才会传入
     * @param string $type 广告类型  images || imagestext  || link
     * @param int $totalnum 发布的总次数
     * @param string  $title 标题
     * @param string $images 文图  类型图片广告
     * @param string $content 文图广告  类型图文比传
     * @param string $video 视频广告  类型视频广告比传
     * @param int $totak 广告点击数  
     * @param string $status 广告的状态
     * @return [type] [description]
     */
    public function publish()
    {  
       if ($this->request->isAjax()) {
        $request = $this->request->request();
        $advertise = new AdvertiseModel();
        $advertise->user_id=$this->auth->id;
        
        switch ($request['type']) {
            case 'link':
                $validete='Advertise.addlink';
                if (strpos($request['content'], 'http://')===false || strpos($request['content'], 'https://')===false) {
                       // $this->success('success');
                }else{
                    $this->error('请按要求填写广告');
                }
                break;
            case 'image':
                $validete='Advertise.addimage';
                break;
            case 'imagetext':
                $validete='Advertise.addimagetext';
                break;
            case 'video':
                $validete='Advertise.addvideo';
                break;
            default:
                $validete='Advertise.addimage';
                break;
        }
        if (!empty($request['id'])) {
            $myad=$advertise->where('user_id',$this->auth->id)->where('status','draft')->where('id',$request['id'])->find();
            if (empty($myad)) {
                $this->error('找不到该广告或广告状态不允许修改');
            }
            $request['status'] = 'draft';
            $result = $advertise->allowField(true)->validate($validete)->save($request,['id'=>$request['id']]);
            $msg='修改成功';
        }else{
          if (empty($request['totalnum'])) {
            $this->error('发布的总条数');
          }
          if (empty($request['content'])) {
             $this->error('内容或链接不能为空');
          }
          if (empty($request['title'])) {
             $this->error('标题不能为空');
          }
            $request['status'] = 'draft';
          $advertise->surplusnum=$request['totalnum'];
            $result = $advertise->allowField(true)->validate($validete)->save($request);
            $msg='发布成功';
        }
       
        if(false === $result){
            $this->error($advertise->getError());
        }else{
            // 这里编写扣除广告条数和扣除记录
            db('user')->where('id',$this->auth->id)->setDec('adnum',$request['totalnum']);
        }
        $this->success($msg);
      }
       return $this->view->fetch('');
    }


    /**
     * 充值短信条数
     * @return [type] [description]
     */
    public function recharge()
    {
        $id = $this->request->request('id',0);
        $num = $this->request->request('num',0);
        $surplus = db('user')->where('id',$this->auth->id)->value('adnum');

        if ($surplus < $num) {
            $this->error('广告数量不足');
        }

        db('user')->where('id',$this->auth->id)->setDec('adnum',$num);

        $advertise = new AdvertiseModel();
        $advertise->where('id',$id)->inc('surplusnum',$num)->inc('totalnum',$num)->update();
        // echo $advertise->getLastSql();
        $this->success('充值成功');

    }
    /**
     * 随机取出一条广告给会员
     * @return [type] [description]
     */
    public function showadvertise()
    {

        if ($this->request->isAjax()) {

            $advertise = new AdvertiseModel();
            $adinfo=$advertise->where('surplusnum','>',0)->where('type','link')->where('status','pass')->orderRaw('rand()')->find();
            $ad_view = config('site.advertise_num');
            $value = $this->auth->getUserExtend('viewad');
            $time = config('site.advertise_time');
            if (empty($adinfo)) {
                return json(['tasknum'=>0,'now'=>0,'time'=>0]);
            }
            if ($adinfo->type == 'link' && !empty($time['link'])) {
                $viewtime = (int)$time['link'];
            }elseif ($adinfo->type == 'imagetext' && !empty($time['imagetext'])) {
                $viewtime = (int)$time['imagetext'];
            }else{
                $viewtime = 10 ;
            }
             
            
            $result = array("info" => $adinfo, "tasknum" => $ad_view,'now' =>$value,'time'=>$viewtime);
            return json($result);
        }
         $ad_view = config('site.advertise_num');
         $value = $this->auth->getUserExtend('viewad');

        return $this->view->fetch('',['ad_view'=>$ad_view,'value'=>$value]);
    }

    /**
     * 观看广告提交观看完成
     * @return [type] [description]
     */
    public function finishad()
    {
        $id = $this->request->request('id',0);
        if ($id <= 0) {
            return json(['code'=>0,'msg'=>'ID错误']);
        }
        $ad_view = config('site.advertise_num');
        $advertise = new AdvertiseModel();
        $advertise->where('id',$id)->dec('surplusnum')->update();
        $value = $this->auth->getUserExtend('viewad');
        if ($ad_view == $value) {
            return json(['code'=>1,'msg'=>'您已经完成了今天的任务']);
        }
        $this->auth->setUserExtend('viewad',++$value);

        if ($ad_view == $value) {
            //调用矿机控制器挖矿方法
            // $rsp = controller('Mineral')->mining();
        }
        return json(['ad_view'=>$ad_view,'surplus'=>$value]);
        
    }
       /**
     * 购买广告条数
     * @param int $num 购买的条数
     * @return [type] [description]
     */
    public function buy(){
          if ($this->request->isPost()) {
                $num = $this->request->post('num');
                if ($num <= 0) {
                   $this->error('请输入正确的条数');
                }
                 $token = $this->request->post('__token__');
                 $rule = [
                   
                ];

                $msg = [
                ];
                $data = [
                    'num'   => $num,
                    '__token__'     => $token,
                ];
                $field = [
                    'num'   => __('请输入正确的条数'),
                ];
                $validate = new Validate($rule, $msg, $field);
                $result = $validate->check($data);
                if (!$result) {
                    $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                    return FALSE;
                }
                $user=$this->auth->getUser();
                $price = config('site.advertise_price');
                $token = $this->auth->getUserToken();

                if ($token->USD < $num) {
                    $this->error('余额不足');
                }
                // 这里编写增加广告条数和扣除USD记录
                User::tokenlog('USD',$this->auth->id,0,-$num,'buyad','买广告');
                db('user')->where('id',$this->auth->id)->setInc('adnum',$num/$price);
                $this->success('购买成功');
          }
       $advertise = new AdvertiseModel();
       $total=$advertise->where('user_id',$this->auth->id)->count();
       $price = config('site.advertise_price');   
      return $this->view->fetch('',['total'=>$total,'price'=>$price]);   
    }
}
